package com.geostar.tbsdemo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;

/**
 * 此 Activity 使用 TBS （腾讯浏览服务）查看文件
 * <br/> 默认支持常见文件类型
 * <br/> <b>默认支持类型：</b>
 * <li>doc</li>
 * <li>docx</li>
 * <li>ppt</li>
 * <li>pptx</li>
 * <li>xls</li>
 * <li>xlsx</li>
 * <li>txt</li>
 * <li>pdf</li>
 * <li>epub</li>
 * <br/>
 * intent参数:
 * <li>filePath - 文件存储路径，如果是在线文件，那么会作为下载路径</li>
 * <li>fileUrl - 在线文件链接</li>
 * <br/>
 * 支持在线文档直接actvity内下载及查看
 *
 * @author hanlyjiang
 * @version 1.1
 */
public class TBSFileViewActivity2 extends AppCompatActivity implements TbsReaderView.ReaderCallback {
    public static final String FILE_PATH = "filePath";
    public static final String FILE_URL = "fileUrl";

    private static final String TAG = "TBSFileViewActivity";
    public static final String TBS_OPEN_FILE_ARGS_filePath = "filePath";
    public static final String TBS_OPEN_FILE_ARGS_tempPath = "tempPath";

    private TbsReaderView mTbsReaderView;
    private ViewGroup rootViewParent;

    private ViewGroup errorHandleLayout;
    private ViewGroup mDownloadLayout;
    private ProgressBar mDownloadProgressBar;

    private String localFilePath;

    /**
     * 文件链接
     */
    private String fileUrl;
    private BaseDownloadTask baseDownloadTask;


    public static void viewFile(Context context, String localPath, String fileUrl) {
        Intent intent = new Intent(context, TBSFileViewActivity2.class);
        intent.putExtra(FILE_PATH, localPath);
        intent.putExtra(FILE_URL, fileUrl);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tbs_file_view_layout2);
        handleIntentAndSetFileInfo();

        if (notHaveLocalFile() && TextUtils.isEmpty(fileUrl)) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            finish();
        }

        getSupportActionBar().setTitle("查看文件：" + getFileName(localFilePath));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        rootViewParent = (ViewGroup) findViewById(R.id.fl_tbs_container_layout);
        mTbsReaderView = new TbsReaderView(this, this);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
        );
        mTbsReaderView.setLayoutParams(layoutParams);
        rootViewParent.addView(mTbsReaderView);

        FrameLayout.LayoutParams layoutParams1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        layoutParams1.gravity = Gravity.CENTER;
        errorHandleLayout = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.error_handle_layout, rootViewParent, false);
        errorHandleLayout.setLayoutParams(layoutParams1);
        initErrorHandleLayout(errorHandleLayout);

        mDownloadLayout = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.download_layout, rootViewParent, false);
        mDownloadProgressBar = mDownloadLayout.findViewById(R.id.progressbar);
        mDownloadLayout.setLayoutParams(layoutParams1);



        if (new File(localFilePath).isFile()) {
            displayLocalFile(localFilePath);
        } else {
            displayOnlineFile(fileUrl, localFilePath);
        }
    }

    private void displayOnlineFile(String fileUrl, String localFilePath) {
        rootViewParent.addView(mDownloadLayout);
        rootViewParent.removeView(errorHandleLayout);
        FileDownloader.setup(this);
        baseDownloadTask = FileDownloader.getImpl().create(fileUrl)
                .setPath(localFilePath)
                .setListener(new FileDownloadListener() {

                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.i("downloadUpdate: ", soFarBytes + " " + totalBytes + " " + totalBytes);
                        if (mDownloadLayout != null) {
                            mDownloadProgressBar.setMax(totalBytes);
                            mDownloadProgressBar.setProgress(soFarBytes);
                        }
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        displayLocalFile(task.getTargetFilePath());
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {

                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                });
        baseDownloadTask.start();
    }

    private boolean notHaveLocalFile() {
        return TextUtils.isEmpty(localFilePath) || !new File(localFilePath).isFile();
    }

    private void initErrorHandleLayout(View errorHandleLayout) {
        errorHandleLayout.findViewById(R.id.btn_retry_with_tbs).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayLocalFile(localFilePath);
            }
        });
        errorHandleLayout.findViewById(R.id.btn_view_with_other_app).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                FileViewer.viewFile4_4(v.getContext(), localFilePath);
            }
        });
    }

    private String getFileName(String filePath) {
        return filePath.substring(filePath.lastIndexOf("/") + 1, filePath.indexOf("."));
    }

    private String handleIntentAndSetFileInfo() {
        if (getIntent() != null) {
            localFilePath = getIntent().getStringExtra(FILE_PATH);
            fileUrl = getIntent().getStringExtra(FILE_URL);
        }
        return null;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCallBackAction(Integer integer, Object long1, Object long2) {
        Log.d(TAG, "onCallBackAction " + integer + "," + long1 + "," + long2);
    }

    private void displayLocalFile(String fileAbsPath) {
        rootViewParent.removeView(mDownloadLayout);

        Bundle bundle = new Bundle();
        bundle.putString(TBS_OPEN_FILE_ARGS_filePath, fileAbsPath);
        bundle.putString(TBS_OPEN_FILE_ARGS_tempPath, Environment.getExternalStorageDirectory().getPath());

        // preOpen 需要文件后缀名 用以判断是否支持
        boolean result = mTbsReaderView.preOpen(parseFormat(fileAbsPath), true);
        if (result) {
            mTbsReaderView.openFile(bundle);
        } else {
            rootViewParent.addView(errorHandleLayout);
        }

    }


    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTbsReaderView.onStop();
        if (baseDownloadTask != null) {
            baseDownloadTask.pause();
        }
    }

}
